import dayjs, { Dayjs } from 'dayjs'
import { pauseRecordingType } from '@/api/customer'

// 格式化时间
export const formattingTime = (date: Date | string | Dayjs | null): string => dayjs(date).format('YYYY-MM-DD')

// 计算是否在时间范围内
export const isInScope = (date: Date | string | Dayjs, startTime: Date | string | Dayjs, endTime: Date | string | Dayjs): boolean => (
  dayjs(date).unix() <= dayjs(endTime).unix() && dayjs(date).unix() >= dayjs(startTime).unix()
)

// 计算天数
export const getDays = (startTime: Date | string | Dayjs, endTime: Date | string | Dayjs): number => (dayjs(endTime).diff(dayjs(startTime), 'day') + 1)

// 计算已配送瓶数
export const getShippedNumber = (_startTime: string, amount: number, distribution: number, pauseRecording: string): number => {
  const toDay = formattingTime(new Date())
  let stopDay = 0
  if (pauseRecording) {
    stopDay = JSON.parse(pauseRecording).reduce((pre: number, cur: pauseRecordingType) => {
      const { stopTime, endStopTime, suspendedDay } = cur
      if (dayjs(toDay).unix() > dayjs(endStopTime).unix()) {
        pre = pre + suspendedDay
      }
      if (isInScope(toDay, stopTime, endStopTime)) {
        pre = pre + getDays(stopTime, toDay)
      }
      return pre
    }, 0)
  }

  const date = dayjs().diff(dayjs(_startTime), 'day') + 1
  const number = Math.floor((date - stopDay) * distribution)
  return number > amount ? amount : number < 0 ? 0 : number
}
